package cn.iocoder.yudao.module.wine.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URISyntaxException;
import java.security.*;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.GET_QRCODE_ERROR;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.HAVE_NO_RIGHT_COMPLAIN;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zyc
 * @createDate 2024/6/3 17:54
 */
public class WeChatUtils {

        //算法名
        public static final String KEY_NAME = "AES";
        // 加解密算法/模式/填充方式
        // ECB模式只用密钥即可对数据进行加密解密，CBC模式需要添加一个iv
        public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

        public static final String accessTokenKey = "WXAccessToken";
        public static final String accessTokenFairLockKey = "WXAccessTokenFairLock";
        public static final String depositPayCallbackLockKey = "depositPayCallbackLock:";
        public static final String depositRefundCallbackLockKey = "depositRefundCallbackLock:";
        static final int TAG_LENGTH_BIT = 128;
    private static final Logger log = LoggerFactory.getLogger(WeChatUtils.class);

    //商户证书私钥
        private PrivateKey merchantPrivateKey;


        //请求客户端
        private CloseableHttpClient httpClient;


        /**
         * 获取微信小程序码
         *
         * @param url
         * @param body
         * @return
         */
        public static ByteArrayOutputStream getWechatQrcodeByHttpURL(String url, Map<String, Object> body) {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = null;
            try {
                StringBuilder builder = new StringBuilder(url);
                String accessToken = (String) body.get("access_token");
                if (StringUtils.isNotBlank(accessToken)) {
                    builder.append("?access_token").append("=").append(accessToken);
                }
                HttpPost httpPost = new HttpPost(builder.toString());
                httpPost.addHeader("Accept", "application/json");
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                body.remove("access_token");
                StringEntity entity = new StringEntity(JSONObject.toJSONString(body));
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                response = httpClient.execute(httpPost);

                log.info("获取小程序码返回：{}",response);

                if (response.getStatusLine().getStatusCode() == 200) {
                    InputStream inputStream = response.getEntity().getContent();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    return out;
                }
                return null;
            } catch (Exception e) {
                throw exception(GET_QRCODE_ERROR);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    /**
     * 获取微信小程序调用凭证
     *
     * @param url
     * @param appid
     * @param secret
     * @return
     */
    public static String getAccessToken(String url, String appid, String secret) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("grant_type", "client_credential"));//参数
            nvps.add(new BasicNameValuePair("appid", appid));
            nvps.add(new BasicNameValuePair("secret", secret));
            uriBuilder.setParameters(nvps);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String responseStr = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(responseStr);
                return (String) jsonObject.get("access_token");
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}
